<template>
  <div class="chart-example">
    <el-card class="chart-card">
      <template #header>
        <div class="chart-header">
          <span>{{ title }}</span>
          <el-radio-group v-model="chartType" size="small" v-if="showControls">
            <el-radio-button value="bar">柱状图</el-radio-button>
            <el-radio-button value="line">折线图</el-radio-button>
            <el-radio-button value="pie">饼图</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <!-- 方式1：直接在容器上使用指令，自动初始化图表 -->
      <div 
        v-if="autoInit"
        class="chart-container"
        v-chart-resize:exampleChart="{options: chartOptions}"
      ></div>
      
      <!-- 方式2：手动初始化图表，然后传递给指令 -->
      <div 
        v-else
        ref="chartContainer" 
        class="chart-container"
        v-chart-resize:exampleChart="chartInstance"
      ></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  title: {
    type: String,
    default: '图表示例'
  },
  showControls: {
    type: Boolean,
    default: true
  },
  autoInit: {
    type: Boolean,
    default: false
  }
})

const chartContainer = ref<HTMLElement | null>(null)
const chartInstance = ref<echarts.ECharts | null>(null)
const chartType = ref('bar')

// 随机生成数据
const generateData = () => {
  return Array.from({ length: 7 }, () => Math.floor(Math.random() * 100 + 20))
}

const data = ref(generateData())
const xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

// 计算图表配置
const chartOptions = computed((): echarts.EChartsOption => {
  if (chartType.value === 'bar') {
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xAxisData
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '数据',
          type: 'bar',
          data: data.value,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }
      ]
    }
  } else if (chartType.value === 'line') {
    return {
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xAxisData
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '数据',
          type: 'line',
          data: data.value,
          lineStyle: {
            width: 3,
            color: '#409EFF'
          },
          emphasis: {
            focus: 'series'
          }
        }
      ]
    }
  } else {
    return {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center'
      },
      series: [
        {
          name: '数据',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: xAxisData.map((item, index) => {
            return {
              name: item,
              value: data.value[index]
            }
          })
        }
      ]
    }
  }
})

// 初始化图表
const initChart = () => {
  if (!chartContainer.value || props.autoInit) return
  
  // 创建图表实例
  chartInstance.value = echarts.init(chartContainer.value)
  
  // 更新图表数据和配置
  updateChart()
}

// 更新图表
const updateChart = () => {
  if (!chartInstance.value || props.autoInit) return
  chartInstance.value.setOption(chartOptions.value)
}

// 刷新数据
const refreshData = () => {
  data.value = generateData()
  if (chartInstance.value && !props.autoInit) {
    updateChart()
  }
}

// 监听图表类型变化
watch(chartType, () => {
  if (props.autoInit) {
    // 自动初始化模式下，数据会自动更新
    refreshData()
  } else {
    updateChart()
  }
})

// 组件挂载时初始化图表
onMounted(() => {
  if (!props.autoInit) {
    initChart()
  }
  
  // 定期刷新数据，模拟实时数据
  setInterval(refreshData, 10000)
})
</script>

<style scoped>
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  width: 100%;
}

/* 确保图表容器可见 */
.chart-card {
  display: flex;
  flex-direction: column;
}

.chart-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
}
</style> 